package com.musicstore.biz.impl;


import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.musicstore.biz.ShoppingCartBiz;
import com.musicstore.dao.AlbumDao;
import com.musicstore.dao.ShoppingCartDao;
import com.musicstore.entity.AlbumEntity;
import com.musicstore.entity.CartItem;
import com.musicstore.entity.ShoppingCart;

@Service("shoppingCartBiz")
public class ShoppingCartBizImpl implements ShoppingCartBiz {
	@Autowired
	private ShoppingCartDao shoppingCartDao;
	@Autowired
	private AlbumDao albumDao;
	
	public void addCartItem(ShoppingCart cart,int id) throws SQLException {	
		System.out.println("进来addCartItem了么");
		CartItem item=findById(cart, id);
		if(item==null) //判断有没有购买过该商品
		{
			AlbumEntity  album=  albumDao.getById(id);
			if(album!=null)
			{
				item=new CartItem();
				item.setId(id);
				item.setTitle(album.getTitle());
				item.setPrice(new BigDecimal(new Random().nextInt(100)));
				item.setQuantity(1);
				cart.getItems().add(item);//添加到购物车
			}			
		}
		else{
			item.setQuantity(item.getQuantity()+1);//数量+1
		}
	}
    //根据id查找购物车是否有数据
	public CartItem findById(ShoppingCart cart,int id)
	{		
		System.out.println("CartItem findById");
		 for (CartItem item : cart.getItems()) {
			if(item.getId()==id)
			{
				return item;				
			}
		}
		return null;
	}
	
	public void removeCartItem(ShoppingCart cart,int id) {		
		CartItem item=findById(cart, id);
		if(item!=null)
			cart.getItems().remove(item);
	}

	public void updateQuantity(ShoppingCart cart,int id, int quantity) {		
		CartItem item=findById(cart, id);
		if(item!=null)
			item.setQuantity(quantity);
	}
}
